package bpm.service.impl.document;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import bpm.dao.document.CommentDao;
import bpm.domain.document.Comment;
import bpm.service.document.CommentService;
import bpm.util.UUID;
/**
 * 
 * @author ZhaoWangLong Sep 16, 2011
 *
 */
@Service("commentService")
@Transactional
public class CommentServiceBean implements CommentService {
	@Resource private CommentDao commentDao;
	private final Logger logger=Logger.getLogger(CommentServiceBean.class);
	public void add(Comment comment) {
		String commentId=UUID.timestamp()+"_DC_COM_"+UUID.randomString(7);
		comment.setCreateTime(new Date());
		comment.setCommentId(commentId);
		logger.debug("Comment : "+comment);
		this.commentDao.save(comment);
	}

	public void delete(Comment comment) {
		this.commentDao.delete(comment);
	}
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public Comment getById(Comment comment) {
		logger.debug("CommentId:"+comment.getCommentId());
		return this.commentDao.getById(comment);
	}
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<Comment> getListByCategory(int[] categorys) {
		StringBuffer sql=new StringBuffer();
		sql.append(" select COMMENT_ID, CATEGORY_ID, CATEGORY_NAME, FIELD_KEY, FIELD_NAME, ")
			.append("  RANK, CREATE_TIME, DESCRIPTION from BPM_DC_COMMENT ");
		if(categorys!=null&&categorys.length>0){
			sql.append(" where FIELD_KEY in ( ");
			StringBuffer temp=new StringBuffer();
			for (int i = 0; i < categorys.length; i++) {
				temp.append(" select FIELD_KEY from BPM_DC_COMMENT  ");
				if(i!=categorys.length-1){
					temp.append(" where  CATEGORY_ID = ").append(categorys[i]).append(" intersect ");
				}else{
					temp.append(" where  CATEGORY_ID = ").append(categorys[i]);
				}
			}
			sql.append(temp.toString()).append(" )  order by  CATEGORY_ID asc ,RANK asc ");
		}
		logger.debug("SQL> "+sql.toString());
		return this.commentDao.getList(sql.toString());
	}

	public void update(Comment comment) {
		this.commentDao.update(comment);
	}

}
